<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

// 初始化页面标题
document.title = "桃丽丝研究所 - 模型中心 - 模型管理";
// 模型列表
const modelList = ref([])
const occupation = [
  {value: 'bladePoint', label: '刀锋'},
  {value: 'Flame', label: '烈焰'},
  {value: 'doubleGun', label: '双枪'},
  {value: 'machineGun', label: '机枪'},
  {value: 'guidedMissile', label: '导弹'},
  {value: 'sniper', label: '狙击'},
  {value: 'medic', label: '医生'},
  {value: 'grenade', label: '榴弹'},
  {value: 'engineer', label: '工程师'}
]
const style = {textAlign: 'center'}
// 模型对话框的可见性
const modelDialogVisible = ref(false);
// 对话框标题
const dialogTitle = ref('');
// 编辑状态标识
const isEditing = ref(false);
// 表单标签宽度
const formLabelWidth = ref('100px')
// 模型表单数据
const modelFormData = ref({
  modelName: '',
  modelOccupation: '',
  modelUrl: '',
  modelImg: '',
});
// 模型表单规则
const modelFormRules = ref({
  modelName: [
    {required: true, message: '请输入模型名称', trigger: 'blur'}
  ],
  modelOccupation: [
    {required: true, message: '请输入模型职业', trigger: 'blur'}
  ],
  modelUrl: [
    {required: true, message: '请输入模型链接', trigger: 'blur'}
  ],
  modelImg: [
    {required: true, message: '请输入模型图片链接', trigger: 'blur'}
  ]
})

// 搜索关键字
const search = ref("")
const occ = ref("")

// 表单组件引用
const modelFormRef = ref(null)
// 总模型数量
const totalModels = ref(modelList.value.length);
// 当前页码，默认为第一页
const currentPage = ref(1);
// 每页显示的条数，默认10
const pageSize = ref(10);
// 页面分页改变时的处理函数


const getModelList = async () => {
  let res;
  try {
    if (search.value) {
      res = await axios.get("/api/model/list", {
        params: {
          search: search.value,
          page: currentPage.value,
          pageSize: pageSize.value
        }
      })
    } else if (occ.value) {
      res = await axios.get("/api/model/list", {
        params: {
          occ: occ.value,
          page: currentPage.value,
          pageSize: pageSize.value
        }
      })
    } else if(search.value && occ.value){
      res = await axios.get("/api/model/list", {
        params: {
          search: search.value,
          occ: occ.value,
          page: currentPage.value,
          pageSize: pageSize.value
        }
      })
    }else {
      res = await axios.get("/api/model/list", {
        params: {
          page: currentPage.value,
          pageSize: pageSize.value
        }
      })
    }
    modelList.value = res.data.data
  } catch (e) {
    ElMessage.error(`服务器异常,获取模型列表失败,请联系管理员！错误：${e.message}`)
  }
}
// 执行搜索
const searchModel = () => {
  getModelList()
}
// 打开添加模型对话框
const openAddModelDialog = () => {
  isEditing.value = false;
  dialogTitle.value = '添加模型';
  modelDialogVisible.value = true;
  modelFormData.value = {modelId: 0, modelName: '', modelOccupation: '', modelUrl: '', modelImg: ''};
}
// 添加模型
const addModel = async () => {
  try {
    const res = await axios.post("/api/model/add", qs.stringify(modelFormData.value))
    if (res.data.code === 200) {
      ElMessage.success("添加模型成功!!")
      modelDialogVisible.value = false;
      await getModelList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (e) {
    ElMessage.error(`服务器异常,添加模型失败,请联系管理员！错误：${e.message}`)
  }
}
// 打开编辑模型对话框
const openEditModelDialog = (model) => {
  isEditing.value = true;
  dialogTitle.value = '编辑模型';
  modelDialogVisible.value = true;
  modelFormData.value = {
    modelId: model.MId,
    modelName: model.MName,
    modelOccupation: model.MOccupation,
    modelUrl: model.MUrl,
    modelImg: model.MImg,
  };
}
// 更新模型
const updateModel = async () => {
  try {
    const res = await axios.post("/api/model/update", qs.stringify(modelFormData.value))
    if (res.data.code === 200) {
      ElMessage.success("更新模型成功!!")
      modelDialogVisible.value = false;
      await getModelList()
    } else {
      ElMessage.error(res.data.msg)
    }
  } catch (e) {
    ElMessage.error(`服务器异常,更新模型失败,请联系管理员！错误：${e.message}`)
  }
}
// 刷新模型列表
const refreshModel = () => {
  search.value = "";
  occ.value = ""
  getModelList()
}
// 删除模型（目前未实现）
const deleteModel = row => {
  ElMessage.warning("删除模型功能暂未开放!")
}
// 确认按钮点击事件，验证表单并提交
const onConfirmButtonClick = () => {
  modelFormRef.value.validate((valid) => {
    if (valid) {
      confirmModelDialog(); // 如果验证通过，则执行模型的添加或更新
    } else {
      ElMessage.error('表单数据有误，请检查后再试');
      return false;
    }
  });
};
// 执行模型添加或更新
const confirmModelDialog = async () => {
  if (isEditing.value) {
    await updateModel(); // 调用编辑模型的API
  } else {
    await addModel(); // 调用添加模型的API
  }
}
// 关闭模型对话框
const closeModelDialog = () => {
  modelDialogVisible.value = false;
}
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage;
  getModelList()
};
// 页面加载时获取模型列表
onMounted(() => {
  getModelList()
})
</script>


<template>
  <!-- 模型容器 -->
  <div class="model_container">
    <el-row>
      <!-- 左侧操作栏 -->
      <el-col :span="12">
        <el-row>
          <!-- 添加模型按钮 -->
          <el-col :span="4">
            <el-button icon="Plus" plain type="primary" @click="openAddModelDialog">发布模型</el-button>
          </el-col>
          <!-- 刷新列表按钮 -->
          <el-col :span="4">
            <el-button icon="Refresh" plain @click="refreshModel">刷新列表</el-button>
          </el-col>
        </el-row>
      </el-col>
      <!-- 右侧搜索栏 -->
      <el-col :span="12">
        <el-row>
          <el-col :span="20">
            <el-row :gutter="20" justify="center">
              <!-- 模型搜索框 -->
              <el-col :span="10">
                <el-input v-model="search" clearable placeholder="请输入模型名称"></el-input>
              </el-col>
              <el-col :span="10">
                <el-select v-model="occ" autocomplete="off" clearable placeholder="请选择职业">
                  <el-option
                      v-for="item in occupation"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                  />
                </el-select>
              </el-col>
              <!-- 搜索按钮 -->
              <el-col :span="4">
                <el-button icon="Search" plain type="primary" @click="searchModel">搜索</el-button>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <!-- 模型列表 -->
    <el-table :data="modelList" :header-cell-style="style" style="width: 100%">
      <el-table-column align="center" label="模型ID" prop="MId" width="120"></el-table-column>
      <el-table-column align="center" label="模型名称" prop="MName" width="300"></el-table-column>
      <el-table-column align="center" label="模型职业" prop="MOccupation" width="200">
        <template #default="scope">
          <div v-for="item in occupation" :key="item.value">
            <el-tag v-if="scope.row.MOccupation === item.value" type="success">
              {{ item.label }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column align="center" label="图片路径" prop="MImg" width="300"></el-table-column>
      <el-table-column align="center" label="下载地址" prop="MUrl" width="300">
        <template #default="scope">
          <div class="ellipsis-cell" :title="scope.row.MUrl">
            {{ scope.row.MUrl }}
          </div>
        </template>
      </el-table-column>
      <!-- 操作栏，包含编辑和删除按钮 -->
      <el-table-column label="操作">
        <template #default="scope">
          <el-button icon="Edit" plain type="primary" @click="openEditModelDialog(scope.row)">编辑</el-button>
          <el-button icon="Delete" plain type="danger" @click="deleteModel(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :background="true"
        :page-sizes="[10, 20, 50, 100]"
        :total="totalModels"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handleCurrentChange"
    />
  </div>
  <el-dialog v-model="modelDialogVisible" :title="dialogTitle" @close="closeModelDialog">
    <!-- 弹窗内容：表单用于编辑或添加模型信息 -->
    <el-form ref="modelFormRef" :model="modelFormData" :rules="modelFormRules">
      <!-- 如果是编辑模式，则显示模型ID，且不可修改 -->
      <el-form-item v-if="isEditing" :label-width="formLabelWidth" label="模型ID">
        <el-input v-model="modelFormData.modelId" autocomplete="off" disabled></el-input>
      </el-form-item>
      <!-- 模型名称输入框 -->
      <el-form-item :label-width="formLabelWidth" label="模型名称" prop="modelName">
        <el-input v-model="modelFormData.modelName" autocomplete="off"></el-input>
      </el-form-item>
      <!-- 模型职业输入框 -->
      <el-form-item :label-width="formLabelWidth" label="模型职业" prop="modelOccupation">
        <el-select v-model="modelFormData.modelOccupation" autocomplete="off" placeholder="请选择职业">
          <el-option
              v-for="item in occupation"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
      </el-form-item>
      <!-- 模型URL输入框 -->
      <el-form-item :label-width="formLabelWidth" label="模型URL" prop="modelUrl">
        <el-input v-model="modelFormData.modelUrl" autocomplete="off"></el-input>
      </el-form-item>
      <!-- 模型图片URL输入框 -->
      <el-form-item :label-width="formLabelWidth" label="模型图片" prop="modelImg">
        <el-input v-model="modelFormData.modelImg" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <!-- 弹窗底部工具栏：包含取消和确定按钮 -->
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeModelDialog">取消</el-button>
        <!-- 在确定按钮上添加表单验证 -->
        <el-button type="primary" @click="onConfirmButtonClick">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-col {
  margin-bottom: 5px;
}
.ellipsis-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.el-table th, .el-table td {
  text-align: center !important;
}
</style>